﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CanDoo;
using CanDoo.Core;
using CanDoo.Core.Data;
using CanDoo.Data;
using CanDoo.Extensions;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Oil.Core.DTOs;
using CanDoo.Oil.Core.Models;
using System.Threading.Tasks;

namespace CanDoo.Oil.Core.Services
{
    /// <summary>
    /// 业务实现——取油码
    /// </summary>
    public class GetOilCodeService : CanDoo.Data.Entity.Services.ServiceBase<GetOilCode>, IGetOilCodeContract
    {
        public IOilSerialNumContract OilSerialNumContract { get; set; }

        /// <summary>
        /// 1.1.3取油码取油
        /// </summary>
        /// <param name="oilCode">取油码</param>
        /// <returns></returns>
        public async Task<OilCodeInfo> GetOilCodeAsync(string oilCode, string terminalNo)
        {
            using (DbScopeFactory.Create())
            {
                var entity = SingleOrDefault(p => p.OilCode == oilCode);
                if (entity == null)
                {
                    return null;
                }

                var oil = OilSerialNumContract.FirstOrDefault(p => p.OilSalesSerialNum.TerminalNum == terminalNo && p.Status == OilSerialStatus.OnSale && p.Product.SN == entity.Oil.SN);
                if (entity == null)
                {
                    throw new Exception("机器上不存在匹配的油品");
                }
                else
                {
                    if (entity.StoreNo.IsEmpty())
                    {
                        entity.StoreNo = terminalNo;
                        UpdateEntity(entity);
                    }
                    else
                        throw new Exception("此取油码被终端号[" + entity.StoreNo + "]锁定");
                }

                var oilCodeInfo = new OilCodeInfo();
                oilCodeInfo.oilId = entity.Oil.SN;
                oilCodeInfo.oilPort = oil.OilPort;
                oilCodeInfo.storeNo = "我们不限制在哪家店购买的,id字段要来干嘛?";
                oilCodeInfo.expireTime = "2010-12-12 23:59:59";
                oilCodeInfo.createTime = entity.CreatedTime.TimeToString("yyyy-MM-dd HH:mm:ss");
                oilCodeInfo.effectiveTime = entity.CreatedTime.TimeToString("yyyy-MM-dd HH:mm:ss");
                oilCodeInfo.id = entity.Id;
                oilCodeInfo.millilitre = entity.Lasted.ToInt();
                oilCodeInfo.oilCode = oilCode;
                oilCodeInfo.memberId = entity.Customer.CardNo;

                if (entity.Lasted > 0)
                    oilCodeInfo.status = 1;
                else
                    oilCodeInfo.status = 2;
                //status 这里1和2 有用吗？ 剩余油量给你就行了
                return oilCodeInfo;
            }
        }
    }
}
